package com.example.toutiao.ui.main.act

import android.R.attr
import android.content.Intent
import android.graphics.Color
import android.text.TextUtils
import android.util.Log
import android.view.View
import android.widget.Toast
import androidx.core.content.ContextCompat
import com.bigkoo.pickerview.builder.TimePickerBuilder
import com.bigkoo.pickerview.listener.OnTimeSelectListener
import com.example.toutiao.R
import com.example.toutiao.base.BaseActivity
import com.example.toutiao.ui.main.model.UserInfoModel
import com.example.toutiao.ui.main.presenter.UpdateUserInfoPresenter
import com.example.toutiao.ui.main.view.UpdateUserInfoView
import com.example.toutiao.ui.user.EvtMsgModel
import com.example.toutiao.utils.CommonUtils.getTime
import com.example.toutiao.utils.Glide4Engine
import com.example.toutiao.view.*
import kotlinx.android.synthetic.main.activity_city.*
import kotlinx.android.synthetic.main.activity_update_user_info.*
import kotlinx.android.synthetic.main.activity_update_user_info.icon_back
import me.bzcoder.mediapicker.SmartMediaPicker
import me.bzcoder.mediapicker.config.MediaPickerEnum
import java.io.File
import java.util.*


open class UpdateUserInfoActivity : BaseActivity<UpdateUserInfoView, UpdateUserInfoPresenter>(),
    UpdateUserInfoView {

    private var photo:String=""
    private var formData:MutableMap<String,String>?= mutableMapOf()
    override fun getLayoutId(): Int = R.layout.activity_update_user_info

    override fun initView() {
        icon_back.setOnClickListener { finish() }

        iv_birth.setUserOnClickListener(object : UserInfoItemView.UserOnClickListener {
            override fun userOnClick(view: View) {
                selectBirthDay()
            }
        })
        iv_area.setUserOnClickListener(object : UserInfoItemView.UserOnClickListener {
            override fun userOnClick(view: View) {
                startActivity(AddressActivity::class.java)
            }
        })

//        下面这部分代码是自定义弹框的代码，目前无法使用--就用了新的组件--主要是 使用 pictureselector 这个插件报错啦
        iv_avatar.setUserOnClickListener(object : UserInfoItemView.UserOnClickListener {
            override fun userOnClick(view: View) {
                selectPhoto()
//                val mPhone = PhotoDialog()
//                mPhone.show(supportFragmentManager, "photodialog")
//                mPhone.setmDialogFragmentListener(object : DialogFragmentListener {
//                    override fun onDialog(type: Int) {
//                        Log.e("photo", type.toString())
//                        if (type == 1) {
//                            selectPhoto()
//                        }
//                    }
//
//                })
            }

        })
        /*性别的监听*/
        iv_sex.setUserOnClickListener(object : UserInfoItemView.UserOnClickListener {
            override fun userOnClick(view: View) {
                val mGender = GenderDialog()
                mGender.show(supportFragmentManager, "genderdialog")
                mGender.setmDialogFragmentListener(object : DialogFragmentListener {
                    override fun onDialog(type: Int) {
                        Log.e("gender", type.toString())
                        if (type == 1) {
                            iv_sex.setRightText("男")
//                            formData?.set("desc", "男")
                            formData!!["desc"]="男"
                            setPart()
                        }
                        if (type == 2) {
                            iv_sex.setRightText("女")
//                            formData?.set("desc", "女")
                            formData!!["desc"]="女"
                            setPart()
                        }
                    }

                })
            }

        })
        iv_username.setUserOnClickListener(object : UserInfoItemView.UserOnClickListener {
            override fun userOnClick(view: View) {
                val mEditDialog = EditTextDialog("请输入用户名")
                mEditDialog.show(supportFragmentManager, "editdialog")
                mEditDialog.setmDialogFragmentListener(object : EditTextDialogListener {
                    override fun onDialog(content: String) {
                        iv_username.setRightText(content)
                        formData?.set("username", content)
                        setPart()
                    }
                })
            }

        })
        iv_phone.setUserOnClickListener(object : UserInfoItemView.UserOnClickListener {
            override fun userOnClick(view: View) {
                val mEditDialog = EditTextDialog("请输入电话")
                mEditDialog.show(supportFragmentManager, "editdialog")
                mEditDialog.setmDialogFragmentListener(object : EditTextDialogListener {
                    override fun onDialog(content: String) {
                        iv_phone.setRightText(content)
                        formData?.set("phone", content)
                        setPart()
                    }
                })
            }

        })
        iv_desc.setUserOnClickListener(object : UserInfoItemView.UserOnClickListener {
            override fun userOnClick(view: View) {
                val mEditDialog = EditTextDialog("请输入简介")
                mEditDialog.show(supportFragmentManager, "editdialog")
                mEditDialog.setmDialogFragmentListener(object : EditTextDialogListener {
                    override fun onDialog(content: String) {
                        iv_desc.setRightText(content)
                        formData?.set("desc", content)
                        setPart()
                    }
                })
            }

        })


    }

    private fun selectBirthDay() {
        val startDate = Calendar.getInstance()
        startDate.set(1900, 1, 1)
        var endDate = Calendar.getInstance()
        TimePickerBuilder(this@UpdateUserInfoActivity,
            OnTimeSelectListener { date, _ ->
                iv_birth.setRightText(getTime(date))
                formData?.set("birthday", getTime(date))
                setPart()
            }).setCancelText("取消")
            .setSubmitText("确认")
            .setCancelColor(ContextCompat.getColor(this@UpdateUserInfoActivity, R.color.c_E6645F))
            .setSubmitColor(ContextCompat.getColor(this@UpdateUserInfoActivity, R.color.c_E6645F))
            .setBgColor(Color.WHITE)
            .setDate(endDate)
            .setRangDate(startDate, endDate)
            .setLabel("年", "月", "日", "时", "分", "秒")
            .setTitleSize(20)
            .build()
            .show()
    }


    override fun initData() {
        getPresenter()!!.getUserInfo(getToken()!!)
    }

    fun selectPhoto() {
//        registerForActivityResult(ActivityResultContracts.TakePicturePreview()){
//            // 返回拍摄的bitmap
//        }.launch(null)
        SmartMediaPicker.builder(this)
            //最大图片选择数目 如果不需要图片 将数目设置为0
            .withMaxImageSelectable(1)
            //最大视频选择数目 如果不需要视频 将数目设置为0
            .withMaxVideoSelectable(1)
            //图片选择器是否显示数字
            .withCountable(true)
            //最大视频长度
            .withMaxVideoLength(15 * 1000)
            //最大视频文件大小 单位MB
            .withMaxVideoSize(1)
            //最大图片高度 默认1920
            .withMaxHeight(1920)
            //最大图片宽度 默认1920
            .withMaxWidth(1920)
            //最大图片大小 单位MB
            .withMaxImageSize(5)
            //设置图片加载引擎
            .withImageEngine(Glide4Engine())
            //前置摄像头拍摄是否镜像翻转图像
            .withIsMirror(false)
            //弹出类别，默认弹出底部选择栏，也可以选择单独跳转
            .withMediaPickerType(MediaPickerEnum.BOTH)
            .build()
            .show()
//        PictureSelector.create(this@UpdateUserInfoActivity)
//            .openGallery(PictureMimeType.ofImage())
//            .maxSelectNum(1)
//            .isCamera(true)
//            .isZoomAnim(true)
//            .circleDimmedLayer(true)
//            .showCropFrame(false)
//            .forResult(PictureConfig.CHOOSE_REQUEST)

    }

    override fun createPresenter(): UpdateUserInfoPresenter = UpdateUserInfoPresenter()

    override fun isRegister(): Boolean = true

    /* 更新用户信息 */
    override fun updateUserInfo(mUserInfo: UserInfoModel) {
        if (mUserInfo != null) {
            iv_phone.setRightText(mUserInfo.phone)
            iv_avatar.setImageUrl(mUserInfo.user_url)
            iv_username.setRightText(mUserInfo.username)
            if (!TextUtils.isEmpty(mUserInfo.desc)) {
                iv_desc.setRightText(mUserInfo.desc)
            } else {
                iv_desc.setTextRightColor(R.color.c_2A8FD6)
                iv_desc.setRightText("待完善")
            }
            if (!TextUtils.isEmpty(mUserInfo.sex)) {
                iv_sex.setRightText(mUserInfo.sex)
            } else {
                iv_sex.setTextRightColor(R.color.c_2A8FD6)
                iv_sex.setRightText("待完善")
            }
            if (!TextUtils.isEmpty(mUserInfo.birthday)) {
                iv_birth.setRightText(mUserInfo.birthday)
            } else {
                iv_birth.setTextRightColor(R.color.c_2A8FD6)
                iv_birth.setRightText("待完善")
            }
            if (!TextUtils.isEmpty(mUserInfo.area)) {
                iv_area.setRightText(mUserInfo.area)
            } else {
                iv_area.setTextRightColor(R.color.c_2A8FD6)
                iv_area.setRightText("待完善")
            }
        }
    }
    fun setPart(){
        getPresenter()!!.updateInfo(formData!!,getToken()!!)
    }
    /* 通知首页更新用户信息 */
    fun postMsg(){
        postMsg(EvtMsgModel(201,getToken()))
    }

    override fun uploadInfo(data: String) {
        if(data!=null){
            postMsg()
            showToast("更新成功")
        }
    }


    override fun <T> setData(data: T) {
        if(data!=null){
            photo=data as String
            /*设置更新后的图片地址*/
            postMsg()
            showToast("更新成功")
        }

    }

    override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
        super.onActivityResult(requestCode, resultCode, data)
        Log.e("img", "$requestCode")
        val resultData = SmartMediaPicker.getResultData(this, requestCode, resultCode, data)
        photo=resultData[0]
        iv_avatar.setImageUrl(photo)
        formData?.set("user_url", photo)
        setPart()
        /*执行上传的操作*/
        getPresenter()!!.uploadImage(File(photo),getToken()!!)
    }

    override fun setError(err: String) {

    }

    override fun getMessage(message: EvtMsgModel<*>) {
        super.getMessage(message)
        if (message != null) {
            if (message.code == 301) {
                iv_area.setTextRightColor(R.color.c_222222)
                iv_area.setRightText(message.msg as String)
                formData?.set("desc", message.msg as String)
                setPart()
            }
        }
    }

}